package com.vrv.common.view;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.vrv.app.R;
import com.vrv.common.resolver.Page;
import com.vrv.common.resolver.RequestParameter;
import com.vrv.common.resolver.Response;
import com.vrv.common.resolver.ResultStatus;
import com.vrv.common.resolver.dispatcher.RequestManager;
import com.vrv.common.utils.StringUtils;
import com.vrv.common.utils.ViewUtils;

/**
 * 通用的数据列表
 *
 * @author 曹保利
 * @version 1.0.0
 *
 */
@SuppressLint("HandlerLeak")
public abstract class CommonListActivity extends Activity {

    /** 标题栏文本 */
    private TextView title;

    /** 标题栏返回按钮 */
    private ImageButton backBtn;

    /** listview组件 */
    private ListView listView;

    /** 通用的数据解析器 */
    private CommonListAdapter adapter = null;

    /** 等待对话框 */
    private ProgressDialog progressDialog;

    /** 结果集 */
    protected List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();

    /** 标题[子类定制] */
    protected String caption = "未知标题";

    /** 详情页面需要展现的字段KEY[子类定制] */
    protected String[] detailKeys = {};

    /** 列表页面需要展现的字段KEY[子类定制] */
    protected String[] listKeys = {};

    /** 请求参数[子类定制] */
    protected RequestParameter parameter = null;

    /** 分页对象暂存 */
    protected Page page = null;

    private View view = null;
    private Button nextBtn = null;
    private Button preBtn = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initTitle();

        findViews();

        prepareData();

        resetTitle();

        initRequest();

        initListeners();
    }

    /**
     * 重置标题
     *
     * @param titleText
     */
    @SuppressWarnings("unused")
    private void resetTitle(String titleText) {
        if (StringUtils.isNullOrEmpty(titleText)) {
            title.setText(caption);
        } else {
            title.setText(titleText);
        }
    }

    /**
     * 重置标题
     *
     * @param titleText
     */
    private void resetTitle() {
        title.setText(caption);
    }

    /**
     * 返回一个可用于请求服务的RequestParameter对象
     *
     * @return
     */
    protected abstract RequestParameter getRequestParameterInstance();

    /**
     * 初始化标题栏
     */
    protected void initTitle() {

        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.common_list_layout);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.common_title);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        title = (TextView) findViewById(R.id.title_text);
        title.setText(caption);

        backBtn = (ImageButton) findViewById(R.id.backBtn);
        backBtn.setVisibility(View.VISIBLE);
        backBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    /**
     * 显示分页按钮以及分页动作
     */
    private void showPageView() {

        if (page.hasNextPage()) {
            nextBtn.setVisibility(View.VISIBLE);
            nextBtn.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    int pageNumber = page.getPageNumber() + 1;
                    requestServer(pageNumber);
                }
            });
        } else {
            nextBtn.setVisibility(View.GONE);
        }
        if (page.hasPrePage()) {
            preBtn.setVisibility(View.VISIBLE);
            preBtn.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    int pageNumber = page.getPageNumber() - 1;
                    requestServer(pageNumber);
                }
            });
        } else {
            preBtn.setVisibility(View.GONE);
        }

        if (page.hasNextPage() || page.hasPrePage()) {
            listView.removeFooterView(view);
            listView.addFooterView(view);
        }
    }

    /**
     * 初始化监听器
     */
    private void initListeners() {
        // 1.跳转到details界面
        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                ArrayList<String> labels = new ArrayList<String>(100);
                ArrayList<String> values = new ArrayList<String>(100);
                for (int i = 0; i < detailKeys.length; i++) {
                    String label = ViewUtils.getStringByKey(getApplicationContext(), detailKeys[i]);
                    String value = String.valueOf(result.get(position).get(detailKeys[i]));
                    labels.add(label);
                    values.add(value);
                }

                Intent intent = new Intent(getApplicationContext(), CommonDetailActivity.class);
                intent.putStringArrayListExtra("labels", labels);
                intent.putStringArrayListExtra("values", values);
                intent.putExtra("caption", caption);

                startActivity(intent);
            }
        });
    }

    /**
     * 初始化必要的数据
     */
    protected abstract void prepareData();

    /**
     * 初次请求服务器
     */
    private void initRequest() {
        parameter = getRequestParameterInstance();
        requestServer(0);
    }

    /**
     * 初始化View
     */
    private void findViews() {
        listView = (ListView) findViewById(R.id.common_list_view);
        view = LayoutInflater.from(CommonListActivity.this).inflate(R.layout.list_page_load, null);
        nextBtn = (Button) view.findViewById(R.id.loadNextButton);
        preBtn = (Button) view.findViewById(R.id.loadPreButton);
    }

    /**
     * 请求服务器
     */
    private void requestServer(int pageNumber) {
        final int index = pageNumber;
        progressDialog = ProgressDialog.show(CommonListActivity.this, "", "查询中...", true, true);
        new Thread(new Runnable() {
            @Override
            public void run() {
                parameter.addArgs("pageNumber", index);
                Log.v("#caobl#", "index:" + index);
                Response response = RequestManager.getInstance(getApplicationContext()).handler(parameter, detailKeys);
                if (response == null) {
                    handler.sendEmptyMessage(ResultStatus.netError.getCode());
                } else if (!response.isSuccess()) {
                    handler.sendEmptyMessage(ResultStatus.bizError.getCode());
                } else if (response.isSuccess() && response.getTotalRecords() > 0 && response.getRecords() != null && response.getRecords().size() > 0) {
                    page = new Page(response, index);
                    result = page.getResult();
                    handler.sendEmptyMessage(ResultStatus.success.getCode());
                } else {
                    handler.sendEmptyMessage(ResultStatus.noneResult.getCode());
                }
            }
        }).start();
    }

    /**
     * 处理数据
     */
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case 0:
                ViewUtils.dismissProgressDialog(CommonListActivity.this, progressDialog, ResultStatus.netError.getMsg());
                break;
            case 1:
                ViewUtils.dismissProgressDialog(CommonListActivity.this, progressDialog, ResultStatus.bizError.getMsg());
                break;
            case 2:
                ViewUtils.dismissProgressDialog(CommonListActivity.this, progressDialog, ResultStatus.noneResult.getMsg());
                break;
            case 3:
                adapter = new CommonListAdapter(CommonListActivity.this, result, listKeys);
                showPageView();
                listView.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                ViewUtils.dismissProgressDialog(CommonListActivity.this, progressDialog, null);
                break;
            default:
                break;
            }
        }
    };
}
